package com.example.springclouduserservice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
//    @LoadBalanced  // 注解原理：拦截器
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("getOrders")
    public String getOrders(){
        ServiceInstance instance = loadBalancerClient.choose("spring-cloud-order-service");
        String url = String.format("http://%s:%s",instance.getHost(),instance.getPort()+"/get");
        return restTemplate.getForObject(url,String.class);
    }
}
